//
//  HNRegisterController.m
//  JHFBaseProject
//
//  Created by 朱传正 on 2016/12/29.
//  Copyright © 2016年 好牛. All rights reserved.
//

#import "HNRegisterController.h"
#import "HNNormalMsgController.h"

@interface HNRegisterController ()

@end

@implementation HNRegisterController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (IBAction)backAction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}



- (IBAction)getCodeAction:(UIButton *)sender {
    [self getVerifyCode];
}


- (IBAction)registerBtn:(UIButton *)sender {
    
    if (!_code.text) {
        [self showHint:@"请先获取邀请码"];
        return;
    }
    if (![_tel.text isMobileNumber]) {
        [self showHint:@"手机号码格式不正确"];
        return;
    }
    if (![_code.text isVerifyNum:6]) {
        [self showHint:@"验证码错误"];
        return;
    }
    if (![_pwd.text isEqualToString:_pwd2.text]) {
        [self showHint:@"两次输入密码不一致"];
        return;
    }
    
    if (![_pwd.text isPassWord]) {
        [self showHint:@"密码长度在6~16位"];
        return;
    }
    
    HNNormalMsgController *normalMsgVC = [[HNNormalMsgController alloc]init];
    normalMsgVC.username = _tel.text;
    normalMsgVC.password = _pwd.text;
    normalMsgVC.captcha = _code.text;
    [self.navigationController pushViewController:normalMsgVC animated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [_getCodeBtn setBackgroundColor: RGB(254, 194, 54)];
    _getCodeBtn.layer.masksToBounds = YES;
    _getCodeBtn.layer.cornerRadius = _getCodeBtn.frame.size.height/2;
    [_registerBtn setBackgroundColor:RGB(84, 207, 84)];
    _registerBtn.layer.masksToBounds = YES;
    _registerBtn.layer.cornerRadius = _registerBtn.frame.size.height/2;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)getVerifyCode{
    if (![_tel.text isMobileNumber]) {
        [self showHint:@"手机号码格式不正确"];
        return;
    }
    [self getCode];
    __block int timeout=59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [_getCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                _getCodeBtn.userInteractionEnabled = YES;
            });
        }else{
            //            int minutes = timeout / 60;
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [_getCodeBtn setTitle:[NSString stringWithFormat:@"已发送(%@)",strTime] forState:UIControlStateNormal];
                _getCodeBtn.userInteractionEnabled = NO;
                
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);

    
}

-(void)getCode{
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:_tel.text,@"phone" ,nil];
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_code parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取验证码失败"];
            return;
        }
        NSLog(@"==dict:%@",data);
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            
            //            [self showHint:@"获取验证码成功"];
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                NSMutableArray *navigationarray = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
                [navigationarray removeAllObjects];
                self.navigationController.viewControllers = navigationarray;
                HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                
                [self.navigationController popToViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取验证码失败"];
    }];

}



@end
